package cn.bjit.controller;


import cn.bjit.enums.BizCodeEnum;
import cn.bjit.enums.ClientTypeEnum;
import cn.bjit.enums.ProductOrderPayTypeEnum;
import cn.bjit.request.ConfirmOrderRequest;
import cn.bjit.service.ProductOrderService;
import cn.bjit.util.JsonData;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Api(tags = "订单模块")
@Slf4j
@RestController
@RequestMapping("/api/order/v1")
public class ProductOrderController {
    @Resource
    private ProductOrderService orderService;

    @ApiOperation("查询订单状态")
    @GetMapping("query_state")
    JsonData queryProductOrderState(@RequestParam("out_trade_no") String outTradeNo) {
        String state = orderService.queryProductOrderState(outTradeNo);

        return StringUtils.isBlank(state) ? JsonData.buildResult(BizCodeEnum.ORDER_CONFIRM_NOT_EXIST) : JsonData.buildSuccess(state);
    }


    @ApiOperation("提交订单")
    @PostMapping("confirm")
    public void confirmOrder(@ApiParam("订单对象") @RequestBody ConfirmOrderRequest orderRequest, HttpServletResponse response) {
        //下单
        JsonData jsonData = orderService.confirmOrder(orderRequest);
        if (jsonData.getCode() == 0) {//下单成功
            //1,获取支付方式
            String payType = orderRequest.getPayType();
            //2，获取终端
            String clientType = orderRequest.getClientType();
            if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.ALIPAY.name())) { //支付宝支付
                if (clientType.equalsIgnoreCase(ClientTypeEnum.H5.name())) { //网页
                    writeDate(response, jsonData);
                } else if (clientType.equalsIgnoreCase(ClientTypeEnum.APP.name())) { //App
                    //APP SDK支付 TODO
                }
            } else if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.WECHAT.name())) { //微信支付
                //微信支付 TODO
            }

        } else {//下单失败
            log.error("创建订单失败:{}", jsonData.toString());
        }
    }

    private void writeDate(HttpServletResponse response, JsonData jsonData) {
        try {
            response.setContentType("text/html;charset=UTF8");
            response.getWriter().write(jsonData.getData().toString());
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            log.error(e.toString());
        }

    }
}

